package com.gitee.xmhzzz.component.tcp.server.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;

/**
 * 算法工具
 */
public class AlgorithmUtil {

	/**
	 * 字节数组转为字符串
	 */
	public static String toHexString(byte[] byteArray) {
		if (byteArray == null || byteArray.length < 1)
			throw new IllegalArgumentException("this byteArray must not be null or empty");

		final StringBuilder hexString = new StringBuilder();
		for (int i = 0; i < byteArray.length; i++) {
			if ((byteArray[i] & 0xff) < 0x10)
				hexString.append("0");
			hexString.append(Integer.toHexString(0xFF & byteArray[i]));
		}
		return hexString.toString().toLowerCase();
	}

	/**
	 * 字符串转为字节数组
	 */
	public static byte[] toByteArray(String hexString) {
		if (hexString == null)
			throw new IllegalArgumentException("this hexString must not be empty");

		hexString = hexString.toLowerCase();
		final byte[] byteArray = new byte[hexString.length() / 2];
		int k = 0;
		for (int i = 0; i < byteArray.length; i++) {// 因为是16进制，最多只会占用4位，转换成字节需要两个16进制的字符，高位在先
			byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);
			byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);
			byteArray[i] = (byte) (high << 4 | low & 0xff);
			k += 2;
		}
		return byteArray;
	}

	public static String aesEncrypt(String message, String passWord) throws GeneralSecurityException, UnsupportedEncodingException {
		return toHexString(aesEncrypt(message.getBytes("UTF-8"), toByteArray(passWord)));
	}

	public static byte[] aesEncrypt(byte[] source, byte rawKeyData[]) throws GeneralSecurityException {
		// 处理密钥
		SecretKeySpec key = new SecretKeySpec(rawKeyData, "AES");
		// 加密
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, key);
		return cipher.doFinal(source);
	}

	public static String aesDecrypt(String message, String passWord) throws GeneralSecurityException {
		return new String(aesDecrypt(toByteArray(message), toByteArray(passWord)));
	}

	public static byte[] aesDecrypt(byte[] data, byte rawKeyData[]) throws GeneralSecurityException {
		// 处理密钥
		SecretKeySpec key = new SecretKeySpec(rawKeyData, "AES");
		// 解密
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, key);
		return cipher.doFinal(data);
	}

	public static void main(String[] args) throws Exception {
		String privateKey = "48ff6e0675845451403907672c5c7e06";
		String str = "{\"a\":\"rs\",\"p\":{\"d\":\"中文\"},\"k\":\"123\"}";
		System.out.println("需要加密字符:" + str);
		String result = aesEncrypt(str, privateKey);
		System.out.println("加密后:" + result);
		String decrypt = aesDecrypt(result, privateKey);
		System.out.println("解密后:" + decrypt);
	}
}
